package com.travelsky.airchina.boarding.web.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.travelsky.airchina.boarding.common.ConstType;
import com.travelsky.airchina.boarding.domain.NewsColumn;
import com.travelsky.airchina.boarding.dto.NewsColumnView;
import com.travelsky.airchina.boarding.service.NewsColumnService;
import com.travelsky.airchina.boarding.web.validator.NewsColumnValidator;
/**
 * 新闻栏目控制类
 * @author haichenwang
 *
 */
@Controller
@RequestMapping(value="/system/newscolumn")
public class NewsColumnController {
	@Autowired
	private NewsColumnService newsColumnService;
	/**
	 * 转到创建新闻栏目页面
	 * @param model
	 * @return
	 */
	@RequestMapping(method=RequestMethod.GET)
	public String toCreate(Model model) {
		List<NewsColumn> newsColumnList = newsColumnService.findNewsColumnsByParentId(null);
		model.addAttribute(newsColumnList);
		NewsColumn newsColumn = new NewsColumn();
		newsColumn.setSortOrder(newsColumnService.getNewsColumnSum());
		model.addAttribute(newsColumn);
		return "system/newscolumn/createForm";
	}
	private void getColumns(Model model,Long columnId,boolean isCreated){
		//if(columnId!=null){
			if(!isCreated){
				NewsColumn newsColumn = newsColumnService.getNewsColumn(columnId);
				List<NewsColumn> rootNewsColumnTemps = newsColumnService.findNewsColumnsByParentId(null);
				List<NewsColumn> rootNewsColumns = new ArrayList<NewsColumn>();
				if(rootNewsColumnTemps!=null){
					for(NewsColumn temp:rootNewsColumnTemps){
						if(!temp.getId().equals(columnId)){
							rootNewsColumns.add(temp);
						}
					}
				}
				List<NewsColumn> parentNewsColumns = newsColumnService.findAllParentNewsColumnsByChildId(columnId);
				List<Long> newsColumnIds = new ArrayList<Long>();
				Map<Long,List<NewsColumn>> map = null;
				if(parentNewsColumns!=null && parentNewsColumns.size()>0){
					for(NewsColumn temp:parentNewsColumns){
						newsColumnIds.add(temp.getId());
					}
					map = newsColumnService.findChildrenNewsColumnByParentId(newsColumnIds,columnId);
					Long rootNewsColumnId = newsColumnIds.get(0);
					model.addAttribute("rootNewsColumnId",rootNewsColumnId);
				}else{
					map = new HashMap<Long,List<NewsColumn>>();
				}
				model.addAttribute("rootNewsColumns",rootNewsColumns);
				model.addAttribute(newsColumn);
				model.addAttribute("map",map);
				model.addAttribute("newsColumnIds",newsColumnIds);
			}else{
				List<NewsColumn> rootNewsColumnTemps = newsColumnService.findNewsColumnsByParentId(null);
				List<NewsColumn> rootNewsColumns = new ArrayList<NewsColumn>();
				if(rootNewsColumnTemps!=null){
					for(NewsColumn temp:rootNewsColumnTemps){
						rootNewsColumns.add(temp);
					}
				}
				List<NewsColumn> parentNewsColumns = newsColumnService.findAllParentNewsColumnsByChildId(columnId);
				List<Long> newsColumnIds = new ArrayList<Long>();
				Map<Long,List<NewsColumn>> map = null;
				if(parentNewsColumns!=null && parentNewsColumns.size()>0){
					for(NewsColumn temp:parentNewsColumns){
						newsColumnIds.add(temp.getId());
					}
					map = newsColumnService.findChildrenNewsColumnByParentId(newsColumnIds);
					Long rootNewsColumnId = newsColumnIds.get(0);
					model.addAttribute("rootNewsColumnId",rootNewsColumnId);
				}else{
					map = new HashMap<Long,List<NewsColumn>>();
				}
				model.addAttribute("rootNewsColumns",rootNewsColumns);
				model.addAttribute("map",map);
				model.addAttribute("newsColumnId",columnId);
				model.addAttribute("newsColumnIds",newsColumnIds);
			}
		//}
	}
	/**
	 * 创建新闻栏目
	 * @param user
	 * @param result
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST)
	public String create(@ModelAttribute("newsColumn") NewsColumn newsColumn, BindingResult result,Model model,HttpServletRequest request) {

		String parentNewsColumnId = request.getParameter("p_cate_id");
		if(null!=parentNewsColumnId && !"-1".equals(parentNewsColumnId) && !"".equals(parentNewsColumnId)){
			NewsColumn parentNewsColumn = new NewsColumn();
			parentNewsColumn.setId(new Long(parentNewsColumnId));
			newsColumn.setParentColumn(parentNewsColumn);
		}
		new NewsColumnValidator().validate(newsColumn,newsColumnService,null,null,result);
		if (result.hasErrors()) {
			if(newsColumn.getParentColumn()!=null && newsColumn.getParentColumn().getId()!=null){
				getColumns(model,newsColumn.getParentColumn().getId(),true);
			}
			model.addAttribute("hasError", true);
			return "system/newscolumn/createForm";
		}
		
		newsColumn.setIsLeaf("1");
		newsColumn.setStatus("1");
		Date createdTime = new Date();
		newsColumn.setCreatedTime(createdTime);
		newsColumn.setLastUpdatedTime(createdTime);
		
		newsColumnService.saveNewsColumn(newsColumn);

		setSessionOperationFlag(request,"t");
		return "redirect:/system/newscolumn/view/"+newsColumn.getId();
	}
	/**
	 * 新闻栏目列表首页
	 * @param id 父新闻栏目的主键
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/manage", method=RequestMethod.GET)
	public String manage(Model model,HttpServletRequest request) {
		List<NewsColumn> newsColumns = newsColumnService.findNewsColumnsByParentId(null);
		model.addAttribute(newsColumns);
		model.addAttribute("manage","manage");
		setRequestOperationFlag(request);
		return "system/newscolumn/newsColumnList";
	}
	/**
	 * 查看新闻列表
	 * @param id 父新闻栏目的主键
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/list/{id}", method=RequestMethod.GET)
	public String list(@PathVariable Long id, Model model) {
		List<NewsColumn> newsColumns = null;
		newsColumns = newsColumnService.findNewsColumnsByParentId(id);
		model.addAttribute(newsColumns);
		NewsColumn newsColumn = newsColumnService.getNewsColumn(id);
		Long parentId = null;
		if(newsColumn!=null && newsColumn.getParentColumn()!=null){
			parentId = newsColumn.getParentColumn().getId();
		}
		model.addAttribute("parentId", parentId);
		return "system/newscolumn/newsColumnList";
	}
	/**
	 * 转到修改新闻栏目页面
	 * @param id 新闻栏目的主键
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
	public String toUpdate(@PathVariable Long id, Model model) {
		getColumns(model,id,false);
		return "system/newscolumn/updateForm";
	}
	/**
	 * 修改新闻栏目
	 * @param newsColumn
	 * @param oldParentNewsColumnId
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public String update(@ModelAttribute("newsColumn") NewsColumn newsColumn, BindingResult result,
			@RequestParam("oldParentColumnId") String oldParentNewsColumnId,
			@RequestParam("p_cate_id") String parentNewsColumnId, 
			@RequestParam("oldNewsColumnName") String oldNewsColumnName, 
			@RequestParam("oldNewsColumnCode") String oldNewsColumnCode, 
			Model model,HttpServletRequest request) {
		Long oldParentNewsColumnIdL = null;
		if(oldParentNewsColumnId!=null && !"".equals(oldParentNewsColumnId)){
			oldParentNewsColumnIdL = new Long(oldParentNewsColumnId);
		}
		if(parentNewsColumnId!=null && !"".equals(parentNewsColumnId) && !"-1".equals(parentNewsColumnId)){
			NewsColumn parentColumn = new NewsColumn();
			parentColumn.setId(new Long(parentNewsColumnId));
			newsColumn.setParentColumn(parentColumn);
		}
		new NewsColumnValidator().validate(newsColumn,newsColumnService,oldNewsColumnName,oldNewsColumnCode,result);
		if (result.hasErrors()) {
			if(newsColumn.getParentColumn()!=null && newsColumn.getParentColumn().getId()!=null){
				getColumns(model,newsColumn.getParentColumn().getId(),true);//此处相当于新增
			}
			model.addAttribute("hasError", true);
			return "system/newscolumn/createForm";
		}
		newsColumnService.updateNewsColumn(newsColumn, oldParentNewsColumnIdL);
		model.addAttribute(newsColumn);
		setSessionOperationFlag(request,"t");
		return "redirect:/system/newscolumn/view/"+newsColumn.getId();
	}
	/**
	 * 查看新闻栏目信息
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/view/{id}", method=RequestMethod.GET)
	public String getView(@PathVariable Long id, Model model,HttpServletRequest request) {
		getColumns(model,id,false);
		setRequestOperationFlag(request);
		return "system/newscolumn/view";
	}
	/**
	 * 通过ajax根据父亲主键获得其下一级栏目
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/childcolumn", method=RequestMethod.GET)
	public @ResponseBody List<NewsColumn> findChildren(@RequestParam Long id) {
		List<NewsColumn> newsColumns = newsColumnService.findNewsColumnsByParentId(id);
		return newsColumns;
	}
	/**
	 * 添加新闻时通过ajax根据父亲主键获得其下一级栏目(需要过滤授权栏目)
	 * @param id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/newschildcolumn", method=RequestMethod.GET)
	public @ResponseBody List<NewsColumnView> findChildrenForNews(@RequestParam Long id,HttpServletRequest request) {
		List<Long> roleColumnIdList = (List<Long>)request.getSession().getAttribute(ConstType.ROLE_NEWS_COLUMN_IDS);
		//List<NewsColumn> newsColumns = newsColumnService.findAuthorityNewsColumnsByParentId(id,roleColumnIdList);
		List<NewsColumnView> newsColumnViews = newsColumnService.findAuthorityNewsColumnViewsByParentId(id,roleColumnIdList);
		return newsColumnViews;
	}
	/**
	 * 通过ajax根据父亲主键获得其下一级栏目
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/childcolumns", method=RequestMethod.GET)
	public @ResponseBody List<NewsColumn> findChildrenForUpdate(@RequestParam Long pId,@RequestParam Long id) {
		List<NewsColumn> newsColumnList = newsColumnService.findNewsColumnsByParentId(pId);
		List<NewsColumn> newsColumns = new ArrayList<NewsColumn>();
		if(newsColumnList!=null && newsColumnList.size()>0){
			for(NewsColumn temp:newsColumnList){
				if(!temp.getId().equals(id)){
					newsColumns.add(temp);
				}
			}
		}
		return newsColumns;
	}
	/**
	 * 通过ajax判断栏目的名称是否已经存在
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/checkColumnName", method=RequestMethod.GET)
	public @ResponseBody boolean checkColumnName(@RequestParam String columnName,@RequestParam String oldColumnName) {
		if(oldColumnName!=null && !"".equals(oldColumnName)){//更新栏目
			if(!oldColumnName.equals(columnName) && newsColumnService.isNewsColumnNameExist(columnName)){
				return true;
			}
		}else{//新建栏目
			if(newsColumnService.isNewsColumnNameExist(columnName)){
				return true;
			}
		}
		return false;
	}
	/**
	 * 通过ajax判断栏目的编码是否已经存在
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/checkColumnCode", method=RequestMethod.GET)
	public @ResponseBody boolean checkColumnCode(@RequestParam String columnCode,@RequestParam String oldColumnCode) {
		if(oldColumnCode!=null && !"".equals(oldColumnCode)){//更新栏目
			if(!oldColumnCode.equals(columnCode) && newsColumnService.isNewsColumnCodeExist(columnCode)){
				return true;
			}
		}else{//新建栏目
			if(newsColumnService.isNewsColumnCodeExist(columnCode)){
				return true;
			}
		}
		return false;
	}

	/**
	 * 删除栏目
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
	public String delete(@PathVariable Long id,HttpServletRequest request) {
		boolean updateFlag = newsColumnService.deleteNewsColumn(id);
		if(updateFlag){
			setSessionOperationFlag(request,"t");
		}else{
			setSessionOperationFlag(request,"f");
		}
		return "redirect:/system/newscolumn/manage";
	}
	/**
	 * 操作后设置操作成功或失败的标志
	 * @param request
	 * @param operationFlag
	 */
	private void setSessionOperationFlag(HttpServletRequest request,String operationFlag){
		request.getSession().setAttribute("operationFlag", operationFlag);
	}
	/**
	 * 从session中取得操作成功或失败的标志,并设置在request
	 * @param request
	 */
	private void setRequestOperationFlag(HttpServletRequest request){
		HttpSession session = request.getSession();
		String operationFlag = (String)session.getAttribute("operationFlag");
		if(operationFlag!=null){
			request.setAttribute("operationFlag", operationFlag);
			session.removeAttribute("operationFlag");
		}
	}
}
